package com.ssl.basics.thread.sync;

/**
 * 描述：
 *
 * @author shi_senlin
 * @create 2021/07/08 22:19
 */
public class NotifyThread {

    public static void main(String[] args) {
        Res res = new Res();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    res.incre();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    res.decre();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    res.incre();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "CC").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    res.decre();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "DD").start();

    }

    static class Res {
        private int number = 0;

        public synchronized void incre() throws InterruptedException {
            while (0 != number) {
                this.wait();
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "--" + number);
            this.notifyAll();
        }

        public synchronized void decre() throws InterruptedException {
            while (1 != number) {
                this.wait();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "--" + number);
            this.notifyAll();
        }
    }
}
